<template>
  <div class="bgc-white" style="display: flex">
    <div class="p16" style="width: 300px; flex-shrink: 0">
      <div class="flex-center-between">
        <span class="fs16 fw500">提成规则</span>
        <span style="display: inline-block; cursor: pointer" @click="onAddGroupItem">
          <a-icon type="plus" />
        </span>
      </div>
      <div class="mt12">
        <a-input-search v-model="rulesName" placeholder="搜索规则名称" style="width: 268px" allowClear @change="onGroupSearchChange" />
      </div>
      <div class="mt16">
        <div
          v-for="item in groupLst"
          :key="item.id"
          class="p8"
          :style="{
            cursor: 'pointer',
            'border-bottom': '1px solid #e8e8e8',
            background: currentGroupId === item.id ? 'var(--primary30)' : 'transparent',
            color: currentGroupId === item.id ? 'var(--primary)' : 'rgba(0, 0, 0, 0.85)'
          }"
          @click="onClickGroupItem(item)"
        >
          {{ item.rulesName }}
        </div>
      </div>
    </div>
    <div v-if="currentGroupTarget" class="p16" style="flex: 1; border-left: 1px solid #e8e8e8; min-height: calc(100vh - 112px)">
      <div class="flex-center-between">
        <div>
          <div class="flex-center">
            <span class="br4 mr8" style="width: 8px; height: 8px; background: var(--primary)"></span>
            <span class="fs16 fw500">{{ currentGroupTarget.rulesName }}</span>
          </div>
          <div class="fs12 mt4" style="color: rgba(102, 102, 102, 1)">规则说明：{{ currentGroupTarget.remark }}</div>
        </div>
        <a-space>
          <a-button type="danger" @click="onDelGroupItem">删除</a-button>
          <a-button type="primary" @click="onEditGroupItem">编辑</a-button>
        </a-space>
      </div>
      <div class="mt16">提成规则</div>
      <div class="mt16">
        <div class="flex-center fw500" style="background: #fafafa; border-bottom: 1px solid #e8e8e8">
          <div class="ta-center p8" style="width: 50%">规则项</div>
          <div class="ta-center p8" style="width: 50%">内容</div>
        </div>
        <div class="flex-center" style="border-bottom: 1px solid #e8e8e8">
          <div class="ta-center p8" style="width: 50%">新购/续费</div>
          <div class="ta-center p8" style="width: 50%">
            新购{{ currentGroupTarget.newProportion }}% 续费{{ currentGroupTarget.continueProportion }}%
          </div>
        </div>
        <div class="flex-center" style="border-bottom: 1px solid #e8e8e8">
          <div class="ta-center p8" style="width: 50%">业务类型</div>
          <div class="ta-center p8" style="width: 50%">{{ currentGroupTarget.subjectType || "--" }}</div>
        </div>
        <div class="flex-center" style="border-bottom: 1px solid #e8e8e8">
          <div class="ta-center p8" style="width: 50%">所属地区</div>
          <div class="ta-center p8" style="width: 50%">
            {{ currentGroupTarget.region ? currentGroupTarget.region.split("_")[1] : "--" }}
          </div>
        </div>
      </div>
      <div class="flex-center mt24">
        <span class="br4 mr8" style="width: 8px; height: 8px; background: var(--primary)"></span>
        <span class="fs16 fw500">{{ currentGroupTarget.rulesName }}绑定的用工单位</span>
      </div>
      <div class="mt16">
        <a-input-search
          v-model="companyOrSaleName"
          placeholder="用工单位/所属销售"
          allowClear
          style="width: 200px"
          @change="onEmpSearchChange"
        />
      </div>
      <a-table
        :dataSource="empLst"
        :pagination="pagination"
        :columns="bindColumns"
        rowKey="companyId"
        size="middle"
        class="mt16"
        @change="onEmpTableChange"
      />
    </div>
    <div v-else class="p16 flex-center-center" style="flex: 1; border-left: 1px solid #e8e8e8; min-height: calc(100vh - 112px)">
      <a-empty />
    </div>
    <a-modal v-model="groupModalVisible" :title="groupModalTitle" :loading="confirmLoadingGroup" @ok="onGroupModalOk">
      <a-form :form="groupForm">
        <a-form-item label="规则名称" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-input
            v-decorator="['rulesName', { rules: [{ required: true, message: '必须填写名称' }] }]"
            placeholder="请输入"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="业务类型" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-input v-decorator="['subjectType']" placeholder="请输入" style="width: 100%" />
        </a-form-item>
        <a-form-item label="所属地区" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-cascader
            v-decorator="['region']"
            :options="common.areaList"
            changeOnSelect
            placeholder="请选择"
            style="width: 100%"
            @change="onRegionChange"
          />
        </a-form-item>
        <a-form-item label="新增提成比例" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-input
            v-decorator="[
              'newProportion',
              {
                rules: [
                  { required: true, message: '必须填写新增提成比例' },
                  {
                    type: 'number',
                    message: '必须填写数字',
                    transform: (value) => {
                      return Number(value);
                    }
                  }
                ]
              }
            ]"
            placeholder="请输入"
            suffix="%"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="续约提成比例" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-input
            v-decorator="[
              'continueProportion',
              {
                rules: [
                  { required: true, message: '必须填写续约提成比例' },
                  {
                    type: 'number',
                    message: '必须填写数字',
                    transform: (value) => {
                      return Number(value);
                    }
                  }
                ]
              }
            ]"
            placeholder="请输入"
            suffix="%"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="规则说明" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-textarea v-decorator="['remark']" placeholder="请输入" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import {
  selectSiteRebatesRulesReq,
  addSaleRebatesRulesReq,
  updateSaleRebatesRulesReq,
  delSaleRebatesRulesReq,
  selectBindCompanyReq
} from "../api";
import { formatRegionValueDe, formatRegionValueEn, bindColumns } from "../funcs";
import { mapState } from "vuex";
export default {
  name: "",
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      bindColumns,
      groupModalTitle: "添加提成规则",
      groupForm: this.$form.createForm(this),
      groupLst: null,
      groupModalVisible: false,
      tempGroup: null,
      currentGroupId: null,
      currentGroupTarget: null,
      empRegionTemp: null,
      confirmLoadingGroup: false,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      companyOrSaleName: "",
      empLst: [],
      rulesName: ""
    };
  },
  computed: {
    ...mapState(["common"]),
    areaSourceMap() {
      return this.common.areaSourceMap;
    }
  },
  watch: {},
  created() {},
  mounted() {
    this.onGroupSearchChange();
  },
  methods: {
    onEmpTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.onEmpSearchChange();
    },
    onEmpSearchChange() {
      const params = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        rulesId: this.currentGroupId
      };
      if (this.companyOrSaleName) {
        params["companyOrSaleName"] = this.companyOrSaleName;
      }
      selectBindCompanyReq(params)
        .then((res) => {
          this.empLst = res.data.entities;
          this.pagination.total = res.data.entityCount;
        })
        .catch((err) => {
          console.log("selectBindCompanyReq", err);
        });
    },
    onRegionChange(value, selectedOptions) {
      this.empRegionTemp = selectedOptions;
    },
    onClickGroupItem(item) {
      this.currentGroupId = item.id;
      this.currentGroupTarget = item;
      this.pagination.current = 1;
      this.onEmpSearchChange();
    },
    onDelGroupItem() {
      this.$confirm({
        title: "删除确认",
        content: "规则删除后将无法恢复，确认要删除吗？",
        onOk: () => {
          delSaleRebatesRulesReq(this.currentGroupTarget.id)
            .then(() => {
              this.$message.success("删除成功");
              this.onGroupSearchChange();
              this.groupModalVisible = false;
            })
            .catch((err) => {
              console.log("deleteGroupReq", err);
            });
        }
      });
    },
    onGroupModalOk() {
      this.groupForm.validateFields((err, values) => {
        if (!err) {
          const newValues = {
            rulesName: values.rulesName,
            subjectType: values.subjectType,
            newProportion: values.newProportion,
            continueProportion: values.continueProportion,
            remark: values.remark
          };
          this.confirmLoadingGroup = true;
          if (this.groupModalTitle === "添加提成规则") {
            newValues["region"] = formatRegionValueEn(this.empRegionTemp);
            addSaleRebatesRulesReq(newValues)
              .then((res) => {
                this.$message.success("添加成功");
                this.onGroupSearchChange();
                this.groupModalVisible = false;
                this.confirmLoadingGroup = false;
              })
              .catch((err) => {
                this.confirmLoadingGroup = false;
                console.log("addSaleRebatesRulesReq", err);
              });
          } else {
            newValues["region"] = formatRegionValueEn(this.empRegionTemp) || this.currentGroupTarget.region;
            updateSaleRebatesRulesReq({
              ...newValues,
              id: this.currentGroupTarget.id
            })
              .then((res) => {
                this.$message.success("修改成功");
                this.onGroupSearchChange();
                this.groupModalVisible = false;
                this.confirmLoadingGroup = false;
              })
              .catch((err) => {
                this.confirmLoadingGroup = false;
                console.log("updateSaleRebatesRulesReq", err);
              });
          }
        }
      });
    },
    onEditGroupItem() {
      this.groupModalTitle = "编辑提成规则";
      this.groupModalVisible = true;
      setTimeout(() => {
        this.groupForm.setFieldsValue({
          rulesName: this.currentGroupTarget.rulesName,
          subjectType: this.currentGroupTarget.subjectType,
          newProportion: this.currentGroupTarget.newProportion,
          continueProportion: this.currentGroupTarget.continueProportion,
          remark: this.currentGroupTarget.remark,
          region: formatRegionValueDe(this.currentGroupTarget.region)
        });
      }, 0);
    },
    onAddGroupItem() {
      this.groupForm.resetFields();
      this.groupModalTitle = "添加提成规则";
      this.tempGroup = null;
      this.groupModalVisible = true;
    },
    onGroupSearchChange() {
      selectSiteRebatesRulesReq(this.rulesName)
        .then((res) => {
          this.groupLst = res.data;
          if (!this.currentGroupId) {
            this.onClickGroupItem(this.groupLst[0]);
          } else {
            const idx = this.groupLst.findIndex((li) => li.id === this.currentGroupId);
            if (idx > -1) {
              this.onClickGroupItem(this.groupLst[idx]);
            } else {
              this.onClickGroupItem(this.groupLst[0]);
            }
          }
        })
        .catch((err) => {
          console.log("selectSiteRebatesRulesReq", err);
        });
    }
  }
};
</script>
<style lang="scss"></style>
